package com.bjsxt.web.filter;

import com.bjsxt.commons.Constants;
import com.bjsxt.pojo.Users;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//注解   看要过虑哪些就给这url
@WebFilter(urlPatterns = {"*.do","*.jsp"})
public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //ServletRequest 是HttpServletRequest的父类 所以要强转
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //取到访问的uri
        String uri = request.getRequestURI();
        //判断取到的地址是login.jsp / login.do  放行
        if(uri.indexOf("login.jsp") != -1 || uri.indexOf("login.do") != -1 || uri.indexOf("validateCode.do")!=-1){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //取得用户对象 在业务层客户与服务端进行会话时，用session建立连接
            //然后根据key-value 取得用户
            HttpSession session = request.getSession();
            Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY);

            //如果users 不为空，证明用户登录过  那么放行
            if(users != null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                //用户没有登录
                request.setAttribute(Constants.REQUEST_MSG,"用户还没有登录");
                request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
            }

        }

    }

    @Override
    public void destroy() {

    }
}
